//
//  EPMHomeViewController.m
//  myXianfeng
//
//  Created by 马继鵬 on 17/4/26.
//  Copyright © 2017年 EPM. All rights reserved.
//

#import "EPMHomeViewController.h"
#import "EPMScanViewController.h"

#import "EPMButton.h"
#import "EPMCatergoryTableViewCell.h"
#import "EPMADTableViewCell.h"
#import "EPMNaviTitleView.h"
#import "EPMSuperMarketViewController.h"
#import "EPMHomeViewModel.h"
#import "EPMCategoryModel.h"


@interface EPMHomeViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,CAAnimationDelegate>

@property (weak,nonatomic) UITableView* tableView;

@property (weak,nonatomic)  EPMNaviTitleView* naviTitleView;

@property (strong,nonatomic) UITabBarItem* item;
///临时商品模型
@property (strong,nonatomic) EPMGoodsModel* tempModel;
@property (assign,nonatomic) BOOL isBlick;

@end
static NSString* Catergory_cell = @"Catergory_cell";
static NSString* AD_cell = @"AD_cell";
@implementation EPMHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    [self setupUI];
     [self addNaviTitleView];
    self.navigationController.delegate = self;
#pragma mark - 设置购物车的显示数据 -
 
    UITabBarItem* item = [self.tabBarController.tabBar.items objectAtIndex:2];
    self.item = item;
    item.badgeColor = [UIColor redColor];
    item.badgeValue = _ShopCar.totalGoodNum == 0 ? nil : [NSString stringWithFormat:@"%zd",_ShopCar.totalGoodNum];
    //接收数据通知
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shopCarGoodsNumChanged:) name:EPMShopCarGoodsNumChanged object:nil];
}

#pragma mark - 通知事件处理 -
- (void)shopCarGoodsNumChanged:(NSNotification*)noti{
    NSInteger num = [noti.userInfo[KShopCarGoodsNum] intValue];
    
    self.item.badgeValue = _ShopCar.totalGoodNum == 0 ? nil :[NSString stringWithFormat:@"%zd",num];
}

#pragma mark - 设置界面 -

- (void)setupUI{
    
    UITableView* tabelView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView = tabelView;
    [self.view addSubview:tabelView];
    
    tabelView.delegate = self;
    tabelView.dataSource = self;
    tabelView.translatesAutoresizingMaskIntoConstraints = YES;
    tabelView.estimatedRowHeight = 300;
//    tabelView.rowHeight = 300;
    [tabelView registerClass:[EPMCatergoryTableViewCell class] forCellReuseIdentifier:Catergory_cell];
    [tabelView registerNib:[UINib nibWithNibName:@"EPMCatergoryTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:Catergory_cell];
    [tabelView registerClass:[EPMADTableViewCell class] forCellReuseIdentifier:AD_cell];
    tabelView.contentInset = UIEdgeInsetsMake(-35, 0, 0, 0);
    
    //接收通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(marketIncreseGoodNotification:) name:EPMHomeIncreaseGoodNotification object:nil];
    
}

#pragma mark - 通知方法 动画-
- (void)marketIncreseGoodNotification:(NSNotification*)noti{
    self.tempModel = noti.userInfo[KIncreaseGoodsModel];
    //获取其实点
    CGPoint startPoint = [noti.userInfo[KIncreaseGoodPoint] CGPointValue];
    // 通过起始点计算 控制点
    CGPoint controlPoint = CGPointMake(startPoint.x + 100, startPoint.y - 50);
    // 终点
    CGPoint endPoint = CGPointMake(ScreenWidth - 150, ScreenHeight - 50);
    UIImage* img = noti.userInfo[KIncreaseGoodImage];
    
    
    UIImageView* imgView = [[UIImageView alloc]initWithImage:img];
    imgView.center = startPoint;
    
    [kWindow addSubview:imgView];
    
    // 创建抛物线路径
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    
    [bezierPath moveToPoint:startPoint];
    [bezierPath addQuadCurveToPoint:endPoint controlPoint:controlPoint];
    
    CAKeyframeAnimation *keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    // 设置路径
    keyFrame.path = bezierPath.CGPath;
    //    keyFrame.removedOnCompletion = NO;
    //    keyFrame.fillMode = kCAFillModeBoth;
    
    
    
    CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:@"transform"];
    scaleAnim.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    //x，y轴缩小到0.1,Z 轴不变
    scaleAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
    //    scaleAnim.removedOnCompletion = NO;
    //    scaleAnim.fillMode = kCAFillModeBoth;
    
    CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnim.fromValue = @(1.0);
    opacityAnim.toValue = @(0.5);
    
    //关键帧，旋转，透明度组合起来执行
    CAAnimationGroup *animGroup = [CAAnimationGroup animation];
    animGroup.animations = [NSArray arrayWithObjects:keyFrame,scaleAnim,opacityAnim, nil];
    animGroup.duration = 1;
    animGroup.delegate = self;
    animGroup.removedOnCompletion = NO;
    animGroup.fillMode = kCAFillModeBoth;
    [animGroup setValue:imgView forKey:@"redBall"];
    [imgView.layer addAnimation:animGroup forKey:nil];
    
    
    
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    
    UIImageView *redBall = [anim valueForKey:@"redBall"];
    
    [redBall removeFromSuperview];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:EPMHomeIncreaseGoodsNotification object:self userInfo:@{KIncreaseGoodsModel:self.tempModel}];
}

#pragma mark - 添加导航栏按键 -

- (void)addNaviTitleView{
    
    EPMNaviTitleView* coverView = [[EPMNaviTitleView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    self.naviTitleView = coverView;
    [self.view insertSubview:coverView aboveSubview:self.tableView];
    self.view.backgroundColor = [UIColor colorWithRed:254/255.0 green:213/255.0 blue:48/255.0 alpha:0.0];
    coverView.controller = self;
}

#pragma mark - 数据源方法 -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0){
        return 1;
    }else {
        return _HomeManager.goodList.count;
    }
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        EPMADTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:AD_cell forIndexPath:indexPath];
        [cell setCategoryDidClickBlock:^(ADCategoryType type) {
            
        }];
        cell.backgroundColor = [UIColor whiteColor];
        return cell;
    }else{
        EPMCatergoryTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:Catergory_cell forIndexPath:indexPath];
//        cell.backgroundColor = [UIColor randomColor];
        cell.activity = _HomeManager.activityList[indexPath.row];
        
        [cell setCatergorySelectedBlock:^(EPMActivityModel* activity){
            self.tabBarController.selectedIndex = 1;
            for (UINavigationController* nav in self.tabBarController.viewControllers){
                
                if ([nav.viewControllers.firstObject isKindOfClass:[EPMSuperMarketViewController class]]){
                    EPMSuperMarketViewController* controller = (EPMSuperMarketViewController*)nav.viewControllers.firstObject;
                    //查询要滚动到的分类
                    NSInteger index = 0;
                    NSInteger count = _MarketManger.catergoryList.count;
                    for (int i = 0 ; i < count; i ++ ){
                        EPMCategoryModel* model = _MarketManger.catergoryList[i];
                        if ([activity.name isEqualToString:model.name]){
                            index = i;
                            //跳转子类
                            [[NSNotificationCenter defaultCenter]postNotificationName:EPMHomeCatergorySelectNotification object:nil userInfo:@{KHomeSelectCatergory:@(index)}];
                            break;
                        }
                    }
                    
                    
                    controller.selectedLeftRow = index;
                }
            }
            
        }];
        return cell;
    }
    
}
#pragma mark - 代理方法 -

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

#pragma mark - 颜色渐变效果 -

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y < 99.0 ){
        CGFloat insert = (scrollView.contentOffset.y - 35.0);
        //小于0保持透明
        if (insert < 0 ) insert = 0;
        [self.naviTitleView setTintalpha:insert/64.0];
        self.isBlick = YES;
        [UIApplication sharedApplication].statusBarStyle= UIStatusBarStyleLightContent;
    }else{
        [self.naviTitleView setTintalpha:1.0];
        self.isBlick = NO;
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1){
        return 360;
    }else{
        return 290;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    //去除点击效果
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    //去除选中效果
    cell.selected = NO;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - UINavigationControllerDelegate代理方法 -

- (void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 如果进入的是当前视图控制器
    if (viewController == self) {
        
        self.navigationController.navigationBar.hidden = YES;
    } else {
        // 进入其他视图控制器
        self.navigationController.navigationBar.alpha = 1;
        // 背景颜色设置为系统默认颜色
        self.navigationController.navigationBar.tintColor = nil;
         self.navigationController.navigationBar.translucent = NO;

    }
   
}
@end
